//
//  MNDSafeSettingViewController.m
//  minidai
//
//  Created by Vitas on 2018/5/31.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDSafeSettingViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "MNDResetPasswordViewController.h"
#import "MNDGestureViewController.h"
#import "MNDResetGestureViewController.h"

@interface MNDSafeSettingViewController ()

@property (weak, nonatomic) IBOutlet UISwitch *fingerprintPwdSwitch;

@property (weak, nonatomic) IBOutlet UISwitch *gestureSwitch;


@end

@implementation MNDSafeSettingViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //根据是否有缓存的手势密码设置手势密码的开关状态
    NSString *gesturePassWord = [UserDefaultsTool objectForKey:kGesturePassword];
    if (gesturePassWord.length > 0) {
        self.gestureSwitch.on = YES;
    }else {
        self.gestureSwitch.on = NO;
    }
    
    //根据是否有缓存指纹设置指纹密码的开关状态
    NSString *fingerPassword = [UserDefaultsTool objectForKey:kFingerPassword];
    if (fingerPassword && fingerPassword.length > 0) {
        self.fingerprintPwdSwitch.on = YES;
    }else {
        self.fingerprintPwdSwitch.on = NO;
    }
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        NSString *gesturePassWord = [UserDefaultsTool objectForKey:kGesturePassword];
        if (gesturePassWord.length > 0) {
            return 3;
        }else {
            return 2;
        }
        
    }else {
        return 1;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(indexPath.section == 0 && indexPath.row == 2) {
        MNDResetGestureViewController *resetGestureVC = [UIStoryboard viewControllerWithIdentifier:@"MNDResetGestureViewController"];
        resetGestureVC.view.backgroundColor = [UIColor whiteColor];
        resetGestureVC.topGestureView.hidden = YES;
        resetGestureVC.topLogImgV.hidden = NO;
        resetGestureVC.forgetGestureButton.hidden = NO;
        [self.navigationController pushViewController:resetGestureVC animated:YES];
    }
    //修改登录密码
    if (indexPath.section == 1 && indexPath.row == 0) {
        
        UIStoryboard *storboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
        MNDResetPasswordViewController *resetVC = [storboard instantiateViewControllerWithIdentifier:@"MNDResetPasswordViewController"];
        [self.navigationController pushViewController:resetVC animated:YES];
    }
    
    
}

//指纹解锁
- (IBAction)fingerSwitchAction:(UISwitch *)sender {
    NSLog(@"%@",sender);
    if (sender.on == YES) {
        [self evaluateAuthenticate];
    }else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定关闭指纹解锁?" message:nil
                                                                  preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            sender.on = YES;
        }];
        UIAlertAction *closeAction = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            sender.on = NO;
            [UserDefaultsTool saveObject:nil forKey:kFingerPassword];
            NSString *fingerLock = [UserDefaultsTool objectForKey:kFingerPassword];
            NSLog(@"%@",fingerLock);
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:closeAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    
}

//指纹解锁验证
- (void)evaluateAuthenticate
{
    //iOS8.0后才支持指纹识别接口
    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
        //弹出，该设备不支持指纹解锁
        self.fingerprintPwdSwitch.on = NO;
        [NetworkProgressHUD showHudMsg:@"该设备不支持指纹解锁"];
        return;
    }
    //创建LAContext
    LAContext* context = [[LAContext alloc] init];
    //    context
    NSError* error = nil;
    NSString* result = @"通过Home键验证已有手机指纹";
    
    //首先使用canEvaluatePolicy 判断设备支持状态
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error]) {
        //支持指纹验证
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                //验证成功，dismiss密码验证 ，弹出指纹开启成功
                self.fingerprintPwdSwitch.on = YES;
                [NetworkProgressHUD showHudMsg:@"指纹解锁开启成功"];
                //                [UserDefaultsTool saveBool:YES forKey:@"fingerSwitchOn"];
                [UserDefaultsTool saveObject:@"YES" forKey:kFingerPassword];
            }
            else
            {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    //其他情况，切换主线程处理
                    self.fingerprintPwdSwitch.on = NO;
                }];
                
                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        //系统取消授权，如其他APP切入
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        //用户取消验证Touch ID
                        break;
                    }
                    case LAErrorAuthenticationFailed:
                    {
                        //授权失败 ，弹出验证失败
                        [NetworkProgressHUD showHudMsg:@"验证失败"];
                        break;
                    }
                    case LAErrorPasscodeNotSet:
                    {
                        //系统未设置密码
                        break;
                    }
                    case LAErrorTouchIDNotAvailable:
                    {
                        //设备Touch ID不可用，例如未打开
                        [NetworkProgressHUD showHudMsg:@"设备未开启指纹功能"];
                        break;
                    }
                    case LAErrorTouchIDNotEnrolled:
                    {
                        //设备Touch ID不可用，用户未录入
                        [NetworkProgressHUD showHudMsg:@"Touch ID不可用"];
                        break;
                    }
                    case LAErrorUserFallback:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //用户选择输入密码，切换主线程处理
                            
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                        }];
                        break;
                    }
                }
            }
        }];
    }
    else
    {
        //不支持指纹识别，LOG出错误详情
        //        NSLog(@"不支持指纹识别");
        //        self.fingerprintPwdSwitch.on = NO;
        //        [NetworkProgressHUD showHudMsg:@"设备不支持指纹识别"];
        
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                //指纹密码错误5次后被禁用
                NSLog(@"TouchID not available");
                break;
            }
        }
        NSLog(@"%@",error.localizedDescription);
    }
}


//手势密码
- (IBAction)gestureSwitchAction:(UISwitch *)sender {
    if (sender.on == YES) {//开启手势
        [self gotoGestureVC];
    }else {//关闭手势
        [self gotoColseGesture];
    }
}

- (void)gotoGestureVC {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Gesture" bundle:nil];
    MNDGestureViewController *gestureViewcontroller = [storyBoard instantiateViewControllerWithIdentifier:@"MNDGestureViewController"];
    gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
    gestureViewcontroller.tipLabel.text = @"请设置手势密码";
    gestureViewcontroller.isCloseGesture = NO;;
    gestureViewcontroller.navigationController.navigationBarHidden = NO;
    [self.navigationController pushViewController:gestureViewcontroller animated:YES];
}

- (void)gotoColseGesture {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Gesture" bundle:nil];
    MNDGestureViewController *gestureViewcontroller = [storyBoard instantiateViewControllerWithIdentifier:@"MNDGestureViewController"];
    gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
    gestureViewcontroller.tipLabel.text = @"请输入原手势密码";
    gestureViewcontroller.topGestureView.hidden = YES;
    gestureViewcontroller.topLogImgV.hidden = NO;
    gestureViewcontroller.isCloseGesture = YES;
    gestureViewcontroller.forgetGestureButton.hidden = NO;
    [self.navigationController pushViewController:gestureViewcontroller animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
